import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;

public class FileUtils {
	public static File createFile(String name, String content) {
		File f = new File (name);
		try {
			f.getParentFile().mkdirs();
			f.createNewFile();
			FileWriter stream = new FileWriter(f);
			BufferedWriter out = new BufferedWriter(stream);
			out.write(content);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return f;
	}

	public static ArrayList<String> readFile(String fileToRead) {
		return readFile(fileToRead, "Cp1251");
	}
	public static ArrayList<String> readFile(String fileToRead, String charsetName) {
		ArrayList<String> out = new ArrayList<>();
		try {
			FileInputStream fstream = new FileInputStream(fileToRead);
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in, charsetName));
			String strLine;
			while ((strLine = br.readLine()) != null)   {
				out.add(strLine);
			}
			in.close();
		} catch (FileNotFoundException e) {
			Log.log("File not found, " + fileToRead, Log.ERROR);
		} catch (IOException e) {
		}
		return out;
	}

	/**
	 * By default File#delete fails for non-empty directories, it works like "rm".
	 * We need something a little more brutual - this does the equivalent of "rm -r"
	 * @param path Root File Path
	 * @throws FileNotFoundException
	 */
	public static void deleteRecursive(File path) throws FileNotFoundException{
		if (!path.exists()) {
			throw new FileNotFoundException(path.getAbsolutePath());
		}

		if (path.isDirectory()){
			for (File f : path.listFiles()){
				FileUtils.deleteRecursive(f);
			}
		}
		else {
			path.delete();
		}
	}

	public static boolean waitForNonEmptyFile(File f, long step, long maxWait) {
		long currentWait = 0;
		while (f.length() == 0 && currentWait < maxWait) {
			try {
				Thread.sleep(step);
				currentWait += step;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return f.length() > 0;
	}
}
